package com.ta.gulimall.product.service.impl;

import com.ta.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ta.gulimall.common.utils.system.PageUtils;
import com.ta.gulimall.common.utils.system.Query;

import com.ta.gulimall.product.dao.BrandDao;
import com.ta.gulimall.product.view.entity.BrandEntity;
import com.ta.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> queryWrapper = new LambdaQueryWrapper<BrandEntity>()
                .eq(StringUtils.isNotBlank(key),BrandEntity::getBrandId, key).or().like(StringUtils.isNotBlank(key),BrandEntity::getName, key);
        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params),queryWrapper);
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateBrand(BrandEntity brand) {
        updateById(brand);
        categoryBrandRelationService.updateCascadeBrand(brand);
    }

    @Override
    public Map<Long, BrandEntity> brandEntityMap(List<Long> brandIds) {
        LambdaQueryWrapper<BrandEntity> wrapper = new LambdaQueryWrapper<BrandEntity>()
                .in(BrandEntity::getBrandId, brandIds);
        Map<Long, BrandEntity> entityMap = list(wrapper).stream().collect(Collectors.toMap(BrandEntity::getBrandId, Function.identity()));

        return entityMap;
    }

}